//index.js
//获取应用实例
const app = getApp();
const api = require('../../utils/api.js');

Page({
  data: {
    curView: "single",
    bindStatus: false,
    hideMask: false,
    gamers: [],
    gamersTemp: [{
        "account_price": 3281,
        "avatar": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1497185593469&di=a9fc038e84c532a32f2de012473a1cd9&imgtype=0&src=http%3A%2F%2Fwww.jf258.com%2Fuploads%2F2013-07-21%2F093652505.jpg",
        "nickname": "哈哈哈哈哈",
        "ranking": {
          "account": 1
        },
        "game_ranking": [
          322330,
          2
        ]
      },
      {
        "account_price": 3281,
        "avatar": "http://file.vgamer.im//face/3d3c635776028224a82b549c980bdb8f_80.jpg",
        "nickname": "啦啦啦啦",
        "ranking": {
          "account": 4
        },
        "game_ranking": [
          322330,
          3
        ]
      },
      {
        "account_price": 3281,
        "avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/34/343776d5c41bd3b777d485ba68e7bfe2f36e93a2.jpg",
        "nickname": "呵呵呵呵呵呵呵呵",
        "ranking": {
          "account": 6
        },
        "game_ranking": [
          322330,
          8
        ]
      }
    ],
    loading: true,
    num: 2,
    user: {
      "nickname": '',
      "wechat": { "avatar": "" }
    },
    kills: [],
    hide: false,
    more: true,
    type: 1,
    ranking: '',
    scene: '',
    groupId: ''
  },
  // 切换tab
  changeView: function(event) {
    let self = this
    let target = event.target;
    let dataset = event.target.dataset;

    if (dataset.view != self.data.curView) {
      switch (dataset.view) {
        case 'single':
          self.data.curView = 'single';
          self.setData({
            type: 1
          })
          self.getRank();
          break;
        case 'double':
          self.data.curView = 'double';
          self.setData({
            type: 2
          })
          self.getRank();
          break;
        case 'five':
          self.data.curView = 'five';
          self.setData({
            type: 3
          })
          self.getRank();
          break;
      }

      this.setData({
        curView: this.data.curView
      })
    }
    this.setData({
      num: 2
    })
  },
  gotoBind() {
    wx.redirectTo({
      url: '../bind/bind'
    })
  },
  // 解绑操作
  unbind() {
    let self = this
    wx.showModal({
      title: '提示',
      content: '确定取消绑定h1z1账号?',
      success: function(res) {
        if (res.confirm) {
          self.unbindFn();
        }
      }
    })
  },
  // 解绑
  unbindFn() {
    let self = this
    let token = wx.getStorageSync("token")
    //console.log(token)
    api.http("h1z1/unbind", "POST", {
      token: token
    }).then((res) => {
      //console.log(res)
      if (res.data.code == 1) {
        this.setData({
          bindStatus: false,
          kills_per_match: '暂无'
        });
        self.getInfo()
      } else {
        wx.showToast({
          title: '解绑失败',
          duration: 1000,
          'user.h1z1': null
        })
      }
    }).catch((res) => {
      self.setData({
        loading: true
      })
      wx.showToast({
        title: "数据获取失败",
        duration: 1000
      });
    })
  },

  // 得到用户绑定信息
  getInfo() {
    let self = this;
    let bindStatus = false;
    let user_id = wx.getStorageSync("user_id");
    let stats = '暂无'
    let kills = []
    api.http("h1z1/getUserInfo", "POST", {
      userId: user_id
    }).then((res) => {
      if (res.data.code == 1) {
        let data = res.data.datas;
        if (res.data.datas.h1z1) {
          kills = self.dealKill(data.h1z1.stats)
          bindStatus = true
        }
        self.getRank();
        self.setData({
          bindStatus: bindStatus,
          user: data,
          kills: kills,
          loading: true
        })
      }
    }).catch((res) => {
      self.setData({
        loading: true
      })
      wx.showToast({
        title: "数据获取失败",
        duration: 1000
      });
    })
  },
  dealArr(arr) {
    let temp = arr
    let tier = ['青铜', '白银', '黄金', '白金', '钻石', '大师', '皇家']
    let type = ['single', 'double', 'five']
    if (arr.length > 0) {
      for (var i = 0; i < arr.length; i++) {
        temp[i].kills_per_match = arr[i].kills_per_match.toFixed(2)
        temp[i].wins_per_match = (arr[i].wins_per_match * 100).toFixed(2)
        temp[i].tier = tier[temp[i].tier - 1] + arr[i].subtier
        temp[i].type = type[temp[i].type - 1]
      }
      return temp;
    } else {
      return;
    }
  },
  dealKill(arr) {
    let temp = arr
    if (arr.length > 0) {
      for (var i = 0; i < 3; i++) {
        temp[i].kill = arr[i].kills_per_match ? arr[i].kills_per_match.toFixed(2) : ''
      }
      return temp;
    } else {
      return;
    }
  },
  // 获得群排行
  getRank() {
    let self = this
    let more = false
    let scene = self.data.scene;
    let type = self.data.type

    if (scene == '1044') {
      this.setData({
        gamers: [],
        loading: false
      })
      if (this.data.groupId == '') {
        api.http('wechat/getGroupId', 'POST', {
          encryptedData: wx.getStorageSync("encryptedData"),
          iv: wx.getStorageSync("iv"),
          token: wx.getStorageSync("token"),
          type: 'h1z1'
        }).then((res) => {
          if (res.data.code == 1) {
            self.setData({
              groupId: res.data.datas
            })
            self.ranking()
          } else {
            self.setData({
              loading: true
            })
          }
        }).catch((res) => {
          self.setData({
            loading: true
          })
          wx.showToast({
            title: "数据获取失败",
            duration: 1000
          });
        })
      } else {
        self.ranking()
      }
    }
  },
  ranking() {
    let self = this
    let type = this.data.type
    let more = false
    api.http("group/h1z1/ranking", "POST", {
      groupId: self.data.groupId,
      token: wx.getStorageSync("token"),
      type: type
    }).then((res) => {
      //console.log(res.data)
      if (res.data.code == 1) {
        let data = res.data.datas
        let ranking = data.me.ranking || '-'
        let group = self.dealArr(data.group)
        let wins
        if (res.data.pages > 1) {
          more = true
        }

        if (data.group.length > 0) {
          self.setData({
            hideMask: true,
            loading: true,
            gamers: group,
            ranking: ranking,
            more: more,
            num: 2,
          })
        } else {
          self.setData({
            hideMask: false,
            loading: true
          })

        }
      } else {
        self.setData({
          loading: true
        })
      }
    }).catch((res) => {
      self.setData({
        loading: true
      })
      wx.showToast({
        title: "数据获取失败",
        duration: 1000
      });
    })
  },
  toInfo(e) {
    let id = e.target.id
    if (id) {
      wx.redirectTo({
        url: '../info/info?id=' + id
      })
    }
  },
  toMe() {
    let id = wx.getStorageSync("user_id")
    if (this.data.user.h1z1) {
      wx.redirectTo({
        url: '../info/info?id=' + id
      })
    }
  },
  //向下滚动加载
  loadMore: function(e) {
    let self = this;
    let num = this.data.num;
    let type = this.data.type;
    let more = false;
    if (this.data.more) {
      this.setData({
        loading: false
      })
      api.http("group/h1z1/ranking", "POST", {
        groupId: this.data.groupId,
        type: type,
        num: num
      }).then((res) => {
        if (res.data.code == 1) {
          let data = res.data.datas
          let gamers = self.data.gamers
          let group = self.dealArr(data.group)
          for (var i = 0; i < group.length; i++) {
            gamers.push(group[i])
          }
          if (res.data.pages > res.data.num) {
            more = true
          }
          if (data.group.length > 0) {
            self.setData({
              hideMask: true,
              gamers: gamers,
              loading: true,
              num: ++num,
              more: more
            })
          } else {
            self.setData({
              loading: true
            })
          }
        } else {
          self.setData({
            loading: true
          })
        }
      }).catch((res) => {
        self.setData({
          loading: true
        })
        wx.showToast({
          title: "数据获取失败",
          duration: 1000
        });
      })
    }
  },
  // 分享
  onShareAppMessage: function() {
    return {
      title: 'h1z1群排行',
      path: 'pages/index/index'
    }
  },
  onLoad: function(ops) {
    var self = this
    let scene = wx.getStorageSync('scene')
    this.setData({
      scene: scene
    })
    //调用应用实例的方法获取全局数据
    app.getUserInfo(function() {
      let user_id = wx.getStorageSync("user_id");
      if (user_id) {
        self.getInfo(user_id);
      }
    })

    wx.showShareMenu({
      //要求小程序返回分享目标信息
      withShareTicket: true
    })
  }
})